<template>
	<view calss="page" style="overflow-x: hidden;">
        <view :style="{height: screenTop+'px'}"></view>
        <uni-nav-bar title="生成密码">
            <view slot="left">
                <uni-icons @click="backAction()" type="back" size="25"></uni-icons>
            </view>
        </uni-nav-bar>

        <!-- 设置临时密码-->
		<template v-if="addType">
			<view class="pass-title">
				请设置临时密码
			</view>
			<view class="code">
				<xt-verify-code size="8" ref="verifyCode" :isFocus="false" inputType="number" cursorColor="#000" class="verify-code" v-model="password">
				</xt-verify-code>
			</view>
			<view class="pass-hint">
				安全密码可用于门锁远程开锁
			</view>
			<view class="pass-header" v-if="false">
				<view class="u-f-ac">
					<view class="">名称</view>
					<input class="input" v-model="passName" type="text" :maxlength="50" placeholder="请给密码命名">
				</view>
				<view class="line"></view>
				<view class="u-f-ac">
					<view class="">密码</view>
					<input class="input" v-model="password" type="number" :maxlength="12" placeholder="请输入7~12位数字密码">
				</view>
			</view>
			<view class="pass-header" style="padding-top: 30rpx;">
				<view class="">
					<view class="u-f-ac pass-name">
						<view class="">密码名称</view>
						<input class="input" v-model="passName" type="text" :maxlength="50" placeholder="请给密码命名" @input="passNameChange">
					</view>
					<view class="line"></view>
					<uni-datetime-picker class="unidatime" style="z-index: 999;" :value="startTime" :start="minStartTime" v-model="startTime"
						@change="changestart" :border="false" :hide-second="true">
						<j-cell title="有效时段起始时间" :more="true" @jftap="jftapstartTime">
							<view slot="tips" class="date">{{startTime?startTime:'选择时间'}}</view>
						</j-cell>
					</uni-datetime-picker>
					<view class="line"></view>
					<uni-datetime-picker style="z-index: 999;" :start="minStartTime" v-model="endTime" @change="changeend" :border="false" :hide-second="true">
						<j-cell title="有效时段终止时间" :more="true" @jftap="jftapstartTime">
							<view slot="tips" class="date">{{endTime?endTime:'选择时间'}}</view>
						</j-cell>
					</uni-datetime-picker>
					<view class="line"></view>
					<j-week class="week" :value="selectedWeeks" @change="changeWeek"></j-week>
				</view>
			</view>
		</template>
        <!-- 临时密码列表页 -->
		<template v-else>
			<view v-if="passList.length == 0" class="u-f-ajc u-f-c noData">
				<image src="https://statics.xmcsrv.net/weixin/noPsdData.png" mode=""></image>
				<text>暂无数据</text>
			</view>
			<scroll-view v-else scroll-y="true" style="height: calc(100vh - 200rpx);" :paging-enabled="true" :refresher-enabled="true" :refresher-threshold="50"  refresher-default-style="white" refresher-background="#f5f7fb" :enable-passive="true" :refresher-triggered="triggered" @refresherrefresh="onRefresh">
				<j-cell-group>
				    <template v-for="(item, index) in passList">
				        <j-cell-slider
							:more="more"
							:key="index"
				            :title="item.name"
							:subTitle="item.startTime + '~'+item.endTime"
				            @jftap="onBindtapPass(item)"
				            @jfdelete="onBinddeletePass(item)"
				        >
						<view slot="tips">
							<text v-if="item.status == 0" class="sync">已同步</text>
							<text v-else-if="item.status == 1 || item.status == 2" class="sync1">未同步</text>
							<text v-else-if="item.status == 3" class="sync1">未同步(已删除)</text>
						</view>
						</j-cell-slider>
				    </template>
				</j-cell-group>
			</scroll-view>
		</template>
		<view class="foot-button">
			<button style="z-index: 888;" v-if="isTemporary == 'save'" class="block radius-btn" @tap="nextstep()"
				:type="addType?'primary':'operation'">{{addType?'保存并复制':'生成密码'}}</button>
		</view>
<!--		<j-doorbell ref="doorbellCall"></j-doorbell>-->
	</view>
</template>

<script>
	// const { date2FmtStr } = require('@/utils/util.js');
	// import getDateTime from '@/jvss/pagesDevice/utils/getdateTime.js';
    const { isEmojiCharacter } = require('@/utils/util.js');
	import moment from 'moment'
	export default {
		data() {
			return {
                oldName: '',
				addType:false,
				isEdit:false,
				passName:'',
				selectedWeeks:[0,1,2,3,4,5,6],
				passList:[],
				title: '请输入6位数字密码',
				device: {},
				tips: 1,
				startTime: '',
				endTime: '',
				vaildNum: 100,
				password: '',
				repeatType:'',
				enable: true,
				verifyCode: "",
				isTemporary: 'save', //是否有临时密码
				selectDate: '',
				weekList:[1,1,1,1,1,1,1],
                dateIndex: 0,
                dateList: [],
				editPassItem:{},
				minStartTime:'',
				triggered:true,
                screenTop: 0,
			}
		},
        watch: {
            passName: {
                handler(newVal, oldVal) {
                    // console.log(isEmojiCharacter(newVal), newVal, oldVal)
                    if(!isEmojiCharacter(newVal)) {
                        this.oldName = newVal
                    }
                },
            }
        },
		onPullDownRefresh() {
			// this.getTailoredConfig()
		},
		onLoad(opt) {
            // 获取手机控制条高度
            const sys = uni.getSystemInfoSync();
            this.screenTop = sys.statusBarHeight
			this.startTime = moment().format("YYYY-MM-DD HH:mm");
			this.endTime = moment(new Date()).add(7, "days").format("YYYY-MM-DD HH:mm");
            this.dateList = [new Date(this.startTime).getDay(), new Date(this.endTime).getDay()]
			this.device = JSON.parse(decodeURIComponent(opt.device))
			this.getTailoredConfig()
            uni.$on('onAlarmEventMessage', (res) => {
				this.AlarmEventInfo(res);
			})
		},
		methods: {
            passNameChange(e) {
                if(isEmojiCharacter(e.detail.value)) {
                    this.$nextTick(() => {
                        this.passName = this.oldName
                    })
                    return
                }
            },
            backAction() {
                // console.log("返回", this.addType);
                if(this.addType) {
                    this.addType = false
                    this.resetData()
                } else {
                    uni.navigateBack()
                }
            },
			onRefresh(){
				this.triggered = true
				this.getTailoredConfig()
				setTimeout(()=>{
					this.triggered = false
				},1000)
			},
			//点击修改密码信息
			onBindtapPass(item){
				this.isEdit = true
				this.addType = true
				setTimeout(()=>{
					this.password = item.password;
				},20)
				this.editPassItem = item
				this.passName = item.name,
				this.startTime = item.startTime
				this.endTime = item.endTime
				let hex = item.rpt.split(' ')[1]
				let str = parseInt(hex,16)
				let bin =  str.toString(2)
				let week = this.buling(bin,7)
				let arr = week.split('')
				let arr2 = []
				arr.forEach((oItem,index)=>{
					if(oItem == '1'){
						arr2.push(arr.length-1-index)
					}
				})
				this.selectedWeeks = arr2
				this.weekList = arr
				this.$forceUpdate()
				// console.log('获取==',hex,str,bin,week,arr,this.selectedWeeks,this.weekList);
			},
			
			//删除密码
			onBinddeletePass(item){
				this.isEdit = true
				this.editPassItem = item
				// this.editPassItem.isDelete = true
				this.setTailoredConfig('delete')
			},
            // 对象比较
            isObjectEqual(obj1, obj2) {
				let json1 = JSON.stringify(obj1)
				let json2 = JSON.stringify(obj2)
				let obj11 = JSON.parse(json1)
				let obj22 = JSON.parse(json2)
				delete obj11.name,
				delete obj22.name
				const obj1Keys = Object.keys(obj11);
				const obj2Keys = Object.keys(obj22);
								
				if (obj1Keys.length !== obj2Keys.length) {
				    return false;
				}
				for (let key of obj1Keys) {
				    if (obj11[key] !== obj22[key]) {
				        return false;
				    }
				}
				return true;
            },
						
			//设置临时密码
			setTailoredConfig(type) {
				if (this.isNull(this.passName) && type != 'delete') {
					return uni.showToast({
						title: '请输入正确名称',
						icon: "none"
					})
				}
				uni.showLoading({
					title:'正在设置',
					mask: true
				});
				let date = new Date()
				let token = this.device.token
				let item = {
					name:this.passName,
					password: this.password,
					startTime: this.startTime,
					endTime: this.endTime,
					rpt: this.binaryToHex(),
					status:1,// 0已同步、1新增、2修改、3已删除（未同步）
					// synchronous:false,
					// isDelete:false
					// id:date.getTime()
				}
				let status = 'del'
				let newArr = []
                let s = true // 判断是否修改过
				if(this.isEdit){
					if(type == 'delete'){
						//未同步的数据 去删除直接删掉这条数据，已同步的数据去删除还保留这条数据 状态显示已删除未同步
						if(this.editPassItem.status==1 || this.editPassItem.status==2){
							this.passList.forEach((oItem,index)=>{
								if(this.editPassItem.id == oItem.id){
									this.passList.splice(index,1)
								}
							})
							newArr = this.passList
							status = 'del'
						}else{
							newArr = this.passList.map((oItem,index)=>{
								if(this.editPassItem.id == oItem.id){
									oItem.status = 3
								}
								return oItem
							})
							status = 'waitSync'
						}
					}else{
						newArr = this.passList.map((oItem,index)=>{
							if(this.editPassItem.id == oItem.id){
							    const status2 = this.editPassItem.status
								oItem = item
							    oItem.status = status2
							    oItem.id = this.editPassItem.id
								console.log();
							    if(!this.isObjectEqual(oItem, this.editPassItem)) {
							        oItem.status = 2
							        s = false
							    }
							}
							return oItem
						})
					}
				}else{
					item.id = date.getTime()%1000000000
				}
				
				let list = this.isEdit?newArr:[...this.passList,item]
				console.log('参数===',list);
				let data = {
					// sn: this.device.deviceNo,
					deviceSn:this.device.deviceNo,
					data: {
						tpswd: {
							list:this.isEdit?newArr:[...this.passList,item]
						}
					}
				};
				getApp().globalData.api.setLxTempPwd(data, (result) => {
				    uni.hideLoading();
				    if(type =='delete'){
				        uni.showToast({
				            title:type=='delete'?(status=='del'?'删除成功':'删除成功等待同步'):'',//设置成功
				            icon:'none',
				            mask:true
				        })
				    }else{
				        wx.setClipboardData({
				            data: this.password,
				            success: (res) => {
				                uni.showToast({
				                    title:'保存并复制成功',//
				                    icon:'none',
				                    mask:true
				                })
				            }
				        })
				    }
				    this.resetData();
				    this.getTailoredConfig();
				    // if(type == 'delete'){
				    // 	this.getDeviceStatus()
				    // }
				});
			},
			// 空格校验
			isNull(str) {
				if (str == "") return true;
				var regu = "^[ ]+$";
				var re = new RegExp(regu);
				return re.test(str);
			},
			//重置数据
			resetData(){
                console.log('qwjerioqw')
				this.addType = false
                // this.dateList = []
				this.isEdit = false
				this.passName = '',
				this.password = ''
				this.startTime = moment().format("YYYY-MM-DD HH:mm");
				this.endTime = moment(new Date()).add(7, "days").format("YYYY-MM-DD HH:mm");
				this.weekList = []
				this.selectedWeeks = []
				this.editPassItem = {}
                console.log(this.startTime, this.endTime)
			},
			// 告警消息
			AlarmEventInfo(res) {
				let info = JSON.parse(res);
				console.log(info, '临时密码页面收到告警消息');
				if (info.SerialNumber == this.device.deviceNo) {
					this.getTailoredConfig();
				}
			},
			//获取临时密码列表
			getTailoredConfig(){
				let token = this.device.token
				let data = {
					// sn: this.device.deviceNo,
					deviceSn:this.device.deviceNo,
					// configs: []
				};
				// getTailoredConfig
				getApp().globalData.api.getLxTempPwd(data, (result) => {
					uni.stopPullDownRefresh()
					if(result.tpswd&&result.tpswd.list){
						this.passList =  result.tpswd.list
					}
					// if(this.passList.length>0){
					// 	this.addType = false
					// }
				})
			},

			// 获取设备状态
			getDeviceStatus(){
				const data = {
					token: [this.device.token]
				};
				getApp().globalData.api.getNewDeviceStatus(data, (result) => {
					let status = result[0]
					if(status.wakeUpStatus === '1'){
						this.login()
					}
				})
			},
			// 同步之前先登录设备
			login(item){
				let token = this.device.token;
				let data = {
					encryptType: 'DISABLE',
					LoginType: 'DVRIP-Web',
					UserName: this.device.devUserName,
					PassWord: this.device.devPassWord,
					Name: 'generalinfo',
					KeepaliveTime: 20
				};
				if (this.device.adminToken) {
					data.LoginToken = this.device.adminToken
					data.encryptType = 'TOKEN'
				}
				if(item){
					uni.showLoading({
						title:'正在同步'
					})
				}
				getApp().globalData.api.deviceLogin(data, token, (result) => {
					let res = result.data
					uni.hideLoading()
					if(res.code == 2000){
						let Ret = res.data.Ret
						if(Ret==100 || Ret==104){
							this.synchronousService()
						}else{
							uni.showToast({
								title:getApp().globalData.errCodeMsg.RetCodeMsg[res.data.Ret]||res.data.RetMsg,
								icon:"none"
							})
							this.$logs({info:'临时密码同步-登录',res:result,data:data},'error')
						}
					}else{
						uni.showToast({
							title: getApp().globalData.errCodeMsg.CodeMsg[res.code]||res.msg,
							icon: 'none'
						});
						this.$logs({info:'临时密码同步--登录',res:result,data:data},'error')
					}
				})
			},
			// 同步
			synchronousService(){
				let token = this.device.token;
				let data = {
				    "Name": "OPDoorLockProCmd",
				    "OPDoorLockProCmd": {
				        "Cmd": "SyncDoorConfig"
				    }
				}
				getApp().globalData.api.opdev(data, token, (result) => {
					if(result.Ret == 100){
						uni.showToast({
							title:'同步成功',
							icon:'none'
						})
						setTimeout(()=>{
							this.getTailoredConfig()
						},2000)
					}else{
						uni.showToast({
							title:getApp().globalData.errCodeMsg.RetCodeMsg[result.Ret] || result.RetMsg,
							icon:'none'
						})
					}
				})
			},
			// 用户输入的值
			vcodeInput(val) {
				this.password = val
			},
            // 计算时间差
            timeDifference() {
                const start = moment(this.startTime).format('YYYY-MM-DD')
                const end = moment(this.endTime).format('YYYY-MM-DD')
                const num = new Date(end) - new Date(start)
                const sa1 = new Date(this.startTime).getDay()? new Date(this.startTime).getDay(): 7
                const sa2 = new Date(this.endTime).getDay()?  new Date(this.endTime).getDay() : 7
                this.dateList = [sa1, sa2]
                console.log(start, end, num)
                let status = true
                let i = (num / 24 / 60 /60 /1000)
                let index = 0
                let arr = [0,0,0,0,0,0,0]
                if(i + 1 <7) {
                    let j = this.dateList[0]
                    let k = this.dateList[1]
                    console.log(j, k, 'jk')
                    console.log(arr, 'arr1');
                    if(j < k) {
                        for (let x = j-1;x<k;x++){
                            arr[x] = 1
                        }
                    } else if(k < j) {
                        for (let y = j-1; y<7;y++) {
                            arr[y] = 1
                        }
                        for (let x = 0; x<k;x++) {
                            arr[x] = 1
                        }
                    } else if(k = j) {
                        arr[k - 1] = 1
                    }
                    console.log(arr, 'arr2');
                    arr.unshift(arr[6])
                    arr = arr.slice(0,7)
                    arr = arr.reverse()
                    let arr2 = arr.map((item, index) => {
                        console.log(item, index, 'arr2-item')
                        if(item === 1) {
                            return index
                        }
                    })
                    console.log(arr, 'arr111')
                    console.log(arr2, 'arr1112')
                    arr2 = arr2.filter(item => {
                        if(item) return item
                        else if(item == 0) {
                            return '0'
                        }
                        return
                    })
                    console.log(arr2, 'arr1113');
                    for (let z = 0; z < arr2.length; z++) {
                        arr[arr2[z]] == this.weekList[arr2[z]] ? index++ : index
                    }
                    if(!index) {
                        status = false
                    }
                    // for (let a = 0; a < 7; a++){
                    //     if(this.weekList[a] > arr[a]) {
                    //         status = false
                    //     }
                    // }
                    return status
                }
                return status
            },
			//生成密码
			nextstep() {
				if(this.addType){
					//生成密码
					if (!this.passName) {
						return uni.showToast({
							title: '请输入密码名称',
							icon: 'none'
						});
					}
                    if(isEmojiCharacter(this.passName)) {
                        return uni.showToast({
                            title: '密码名称禁止使用表情包',
                            icon: 'none'
                        });
                    }
					if (!this.password) {
						return uni.showToast({
							title: '请输入密码',
							icon: 'none'
						});
					}
					if (this.password.length < 8) {
						return uni.showToast({
							title: '密码不得低于8位',
							icon: 'none'
						});
					}
					if(this.dateIndex === 7){
						return uni.showToast({
							title: '请选择星期',
							icon: 'none'
						});
					}
                    const s = this.timeDifference()
                    if(!s) {
                        return uni.showToast({
                            title: '有效期异常，未包含所选择的星期',
                            icon: 'none'
                        });
                    }
					if (!this.startTime) {
						return uni.showToast({
							title: '请选择开始时间',
							icon: 'none'
						});
					}
					if (!this.endTime) {
						return uni.showToast({
							title: '请选择结束时间',
							icon: 'none'
						});
					}
					if (this.compareDate(this.startTime, this.endTime)) {
						return wx.showModal({
							title: '提示',
							content: '结束时间不得小于或等于开始时间,请重新选择',
							confirmText: '确定',
							showCancel: false,
							success: (res) => {
								
							}
						})
					}
					this.weekList.unshift(0)
					this.setTailoredConfig()
				}else{ 
					//新增密码
					if(this.passList.length == 10){
						uni.showToast({
							title:'最多只能设置10个密码',
							icon:'none'
						})
						return
					}
					this.selectedWeeks = [0,1,2,3,4,5,6],
					this.weekList = [1,1,1,1,1,1,1],
					this.addType = true
					let num = this.passList.length
					this.passName = '临时密码'+ num
				}
			},
			
			// 选择星期
			changeWeek(value) {
				this.selectedWeeks = value
				console.log('选择星期',value);
				// 0,1,2,3,4,5,6  对应周日、一、二、三、四、五、六
				let arrStr = [0,0,0,0,0,0,0]
				if(value.includes(0)){
					arrStr[arrStr.length-1]=1
				}
				if(value.includes(1)){
					arrStr[arrStr.length-2]=1
				}
				if(value.includes(2)){
					arrStr[arrStr.length-3]=1
				}
				if(value.includes(3)){
					arrStr[arrStr.length-4]=1
				}
				if(value.includes(4)){
					arrStr[arrStr.length-5]=1
				}
				if(value.includes(5)){
					arrStr[arrStr.length-6]=1
				}
				if(value.includes(6)){
					arrStr[arrStr.length-7]=1
				}
				this.weekList = arrStr
                let i = 0
                arrStr.forEach(item => item === 0 ? i++ : i)
                this.dateIndex = i
				console.log('this.weekList',arrStr);
			},
			//开始时间
			changestart(v) {
				console.log('开始时间===',v);
				this.startTime = v //new Date(v.replace(/-/g,'/'))
                let day = new Date(v).getDay()
                day === 0 ? day = 7 : day
                this.dateList[0] = day
			},
			//结束时间
			changeend(v) {
				console.log('结束时间',v);
				// this.endTime = new Date(v.replace(/-/g,'/'))
				this.endTime = v
                let day = new Date(v).getDay()
                day === 0 ? day = 7 : day
                this.dateList[1] = day
			},
			//比对时间
			compareDate(date1, date2) {
				let dates1 = new Date(date1); //当前时间
				let dates2 = new Date(date2); //结束时间
				console.log('date1',dates1);
				console.log('date2',dates2);
				console.log('date2',dates2,dates1 > dates2);
				if (dates1 >= dates2) {
					return true;
				} else {
					return false;
				}
			},
			//二进制转十六进制
			binaryToHex(){
				let decimal = ''
				let hex = ''
				if(this.weekList.length==0){
					hex = 'once'
				}else{
					let str = this.weekList.join('')
					decimal = parseInt(str,2)
					hex ='week'+' '+'0x'+ decimal.toString(16)
				}
				return hex
			},
			//二进制补零
			buling(a, length) {
				return a.padStart(length,0)
			},
			jftapstartTime() {
				this.minStartTime = new Date().getTime()
			},
			jftapendTime() {},
		}
	}
</script>

<style lang="scss">
	.verify-code {
		.xt__verify-code {
			// width: 80% !important;
			margin: auto;
	
		}
	
		.xt__input-ground {
			margin: auto;
	
			.xt__code-text {
				font-size: 40rpx !important;
	
			}
		}
	
		/deep/.xt__code-text {
			font-size: 40rpx !important;
	
		}
	
		/deep/.xt__box {
			width: 70rpx !important;
			height: 70rpx !important;
			background: #fff;
			border-radius: 10rpx;
			border: #eee;
			border-width: 1px !important;
			border-style: solid !important;
		}
	}
	
	.code {
		margin-top: 50rpx;
		margin: 50rpx 11px;
	}
	.pass-title{
		margin: 50rpx 11px;
		font-weight: bold;
		color: #000000;
		font-size: 36rpx;
		text-align: center;
	}
	.pass-hint{
		font-size: 26rpx;
		color: #A2A2A2;
		margin-bottom: 50rpx;
		text-align: center;
	}
	.pass-header {
		display: flex;
		background: #fff;
		margin: 11px 11px 0 11px;
		border-radius: 5px;
		padding:20rpx 20rpx;
		font-size: 28rpx;
		flex-direction: column;
		box-sizing: border-box;
		.line{
			// width: 623rpx;
			margin: 10rpx 0rpx;
			height: 1px;
			background: #EEEEEE;
		}
		.input{
			margin-left: 30rpx;
			width: 70%;
			font-size: 26rpx;
		}
		.pass-name{
			height: 80rpx;
			font-size: 30rpx;
			padding: 0 20rpx;
			.input{
				margin-left: 30rpx;
				width: 70%;
				font-size: 26rpx;
				text-align: right;
			}
		}
		.week{
			margin: 20rpx;
			.weeks{
				margin-bottom: 0;
			}
		}
	}
	.block[type='primary']{
		width: 96% !important;
	}
	.bottm {
		position: fixed;
		left: 30rpx;
		right: 30rpx;
		bottom: 40rpx;
		height: 84rpx;
		background: rgba(255, 255, 255, 0.39);
		border: 1rpx solid #B9B9B9;
		border-radius: 15rpx;
		ont-size: 30rpx;
		color: #FF0025;
		font-weight: 700;
	}
	.date{
		font-size: 26rpx;
		color: #666;
	}
	.sync{
		font-size: 26rpx;
		margin-right: 20rpx;
		color: #FF0025;
	}
	.sync1{
		font-size: 26rpx;
		margin-right: 20rpx;
		color: red;
	}
	.noSync{
		font-size: 26rpx;
		margin-right: 20rpx;
		padding: 10rpx;
		border-radius: 5rpx;
		border:1px solid #FF0025;
		color: #FF0025;
	}
	/deep/.cell-tips{
		font-size: 24rpx;
		color: #999999;
		max-width: 60vw !important;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	.noData{
		margin-top: 300rpx;
		image{
			width: 214rpx;
			height: 146rpx;
		}
		text{
			margin-top: 20rpx;
			color:#CDCDCE;
			font-size: 24rpx;
		}
	}
	.unidatime {
		// border: 1px solid red;
	}

	.uniui-calendar {
		display: none;
	}

	.uniui-clear {
		display: none;
	}

	.uni-date__x-input {
		padding: 0;
	}
	.uni-input {
		// border: 1px solid rebeccapurple;
		width: 300rpx;
		height: 45px;
		line-height: 45px;
		text-align: right;
	}
</style>
